
<template>
  <div>
    <h1>测试测试</h1>
    <el-upload
      class="upload-demo"
      ref="upload"
      action="http://localhost:9999/api/UploadImages/G1027_测3099"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :show-file-list="true"
      :multiple="true"
      :limit="5"
      :before-upload="beforeUpload"
      :on-exceed="exceed"
      :file-list="fileList"
      :auto-upload="false">
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
    <input type="file" @change="calculate" />
  </div>
</template>
<script>
import CryptoJs from 'crypto-js'
import encHex from 'crypto-js/enc-hex'
import { Post } from '../network/request'
/**
 * 用于计算文件的hash值，包括sha256值和md5值
 */
function hashFile (file) {
  /**
   * 使用指定的算法计算hash值
   */
  function hashFileInternal (file, alog) {
    // 指定块的大小，这里设置为20MB,可以根据实际情况进行配置
    const chunkSize = 20 * 1024 * 1024
    let promise = Promise.resolve()
    // 使用promise来串联hash计算的顺序。因为FileReader是在事件中处理文件内容的，必须要通过某种机制来保证update的顺序是文件正确的顺序
    for (let index = 0; index < file.size; index += chunkSize) {
      promise = promise.then(() => hashBlob(file.slice(index, index + chunkSize)))
    }

    /**
     * 更新文件块的hash值
     */
    function hashBlob (blob) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = ({ target }) => {
          const wordArray = CryptoJs.lib.WordArray.create(target.result)
          // 增量更新计算结果
          alog.update(wordArray)
          resolve()
        }
        reader.readAsArrayBuffer(blob)
      })
    }

    // 使用promise返回最终的计算结果
    return promise.then(() => encHex.stringify(alog.finalize()))
  }

  // 同时计算文件的sha256和md5,并使用promise返回
  return Promise.all([hashFileInternal(file, CryptoJs.algo.SHA256.create()),
    hashFileInternal(file, CryptoJs.algo.MD5.create())])
    .then(([sha256, md5]) => ({
      sha256,
      md5
    }))
}
export default {
  name: "Test",
  data() {
    return {
      msg: 'Welcome to Your',
      fileList: []
    }
  },
  methods: {
    calculate ({ target: { files } }) {
      for (const file of files) {
        hashFile(file).then(console.log)
      }
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    exceed(files,fileList){
      alert(fileList.length);
    },
    beforeUpload(file){
      hashFile(file).then(console.log)
    },
    submit(){
      console.log('手动上传')
    }
  }
}
</script>
